package net.qiqbframework.messaging.monitoring;


import net.qiqbframework.common.Assert;
import net.qiqbframework.messaging.Message;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MultiMessageMonitor<T extends Message<?>> implements MessageMonitor<T> {

    private final List<MessageMonitor<? super T>> messageMonitors;

    @SafeVarargs
    public MultiMessageMonitor(MessageMonitor<? super T>... messageMonitors) {
        this(Arrays.asList(messageMonitors));
    }


    public MultiMessageMonitor(List<MessageMonitor<? super T>> messageMonitors) {
        Assert.notNull(messageMonitors, () -> "MessageMonitor list may not be null");
        this.messageMonitors = new ArrayList<>(messageMonitors);
    }


    @Override
    public MonitorCallback onMessageIngested(@Nonnull T message) {
        final List<MonitorCallback> monitorCallbacks = messageMonitors.stream()
                .map(messageMonitor -> messageMonitor.onMessageIngested(
                        message))
                .toList();

        return new MonitorCallback() {
            @Override
            public void reportSuccess() {
                monitorCallbacks.forEach(MonitorCallback::reportSuccess);
            }

            @Override
            public void reportFailure(Throwable cause) {
                monitorCallbacks.forEach(resultCallback -> resultCallback.reportFailure(cause));
            }

            @Override
            public void reportIgnored() {
                monitorCallbacks.forEach(MonitorCallback::reportIgnored);
            }
        };
    }
}
